package com.storm.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

/**
 * use this to record logs,
 * @author liuquan
 * @date 2013-11-26
 *
 */
public class Log {
	
	private static String logFolder = "D:\\test\\";//we should get this from the config file
	private static String logFile = "";// every day we create a new file
	private static String errFile = "";// every day we create a new file
	private static PrintStream logStream = null;
	private static PrintStream errStream = null;
	static{
		checkLogFolder();
		checkLogFile();
		setIOStream();
	}
	/**
	 * check if the log folder is exits, if not , then create it
	 */
	public static void checkLogFolder(){
		File folder = new File(logFolder);
		if(folder.isDirectory()){
			if(!folder.exists()){
				folder.mkdirs();
			}
		}
	}
	/**
	 * check if the log file is exits, if not, then create it.
	 */
	public static void checkLogFile(){
		logFile = logFolder+ "Log " + UDate.getByDay();
		File log = new File(logFile);
		if(!log.exists()){
			try {
				log.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		errFile = logFolder+ "Err " + UDate.getByDay();
		File err = new File(logFile);
		if(!err.exists()){
			try {
				err.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}

	/**
	 * redirect the output stream to the log file
	 */
	public static void setIOStream(){
		try {
			logStream = new PrintStream(new FileOutputStream(logFile,true));
			errStream = new PrintStream(new FileOutputStream(errFile,true));
			System.setOut(logStream);
			System.setErr(errStream);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}  
		
	}
	/**
	 * write a log to the log file. the log file split by day.
	 * @param Content
	 */
	public static void writeLog(String content){
		if(content == null || content.equals("")){
			return;
		}
		System.out.println(content);
		
	}
	/**
	 * write the error info to the error file
	 * @param content
	 */
	public static void writeErr(String content){
		if(content == null || content.equals("")){
			return;
		}
		System.err.println(content);
	}
	
	public static void main(String[] args){
		Log.writeLog("log");
		Log.writeErr("err");
		try{
			int a = 5/0;
			System.out.println(a);
		}catch(Exception e){
			e.printStackTrace();//auto write this message to the error file
		}
		
	}

}
